import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    const user = getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    // 获取统计数据
    const [totalVideos, totalTexts, totalUsers, totalTasks, runningTasks, recentActivity] = await Promise.all([
      // 总视频数
      prisma.tikTokVideo.count(),

      // 总文案提取数
      prisma.textExtraction.count({
        where: { status: 'completed' }
      }),

      // 总用户数
      prisma.user.count(),

      // 总任务数
      prisma.extractionTask.count(),

      // 运行中的任务数
      prisma.extractionTask.count({
        where: { status: 'running' }
      }),

      // 今日活动数（今天创建的视频、文案提取记录和任务）
      prisma.tikTokVideo.count({
        where: {
          createdAt: {
            gte: new Date(new Date().setHours(0, 0, 0, 0))
          }
        }
      }).then(async (todayVideos) => {
        const todayTexts = await prisma.textExtraction.count({
          where: {
            createdAt: {
              gte: new Date(new Date().setHours(0, 0, 0, 0))
            }
          }
        })
        const todayTasks = await prisma.extractionTask.count({
          where: {
            createdAt: {
              gte: new Date(new Date().setHours(0, 0, 0, 0))
            }
          }
        })
        return todayVideos + todayTexts + todayTasks
      })
    ])

    return NextResponse.json({
      totalVideos,
      totalTexts,
      totalUsers,
      totalTasks,
      runningTasks,
      recentActivity
    })

  } catch (error) {
    console.error('Stats fetch error:', error)
    return NextResponse.json(
      { error: '获取统计数据失败' },
      { status: 500 }
    )
  }
}
